import axios from "axios"
import { store } from "@/store"
import { router } from "@/router"

// 创建axios实例
const instance = axios.create({
    baseURL: "/api/v1/admin",
    timeout: 30000,
})

// 请求失败后的错误统一处理
function errorHandle(status: number, message: any) {
    const to = router.currentRoute.value
    const query: any = {}

    if (["/", "/home"].indexOf(to.path) < 0) {
        query["origin"] = to.fullPath
    }

    switch (status) {
        case 400:
            window.$message.error(message)
            break
        case 401:
            // 认证失败
            store.commit("logout")

            if (to.path != "/login") {
                router.push({
                    path: "/login",
                    query: query,
                })
            }

            break
        case 403:
            window.$message.error("禁止访问")
            break
        case 404:
            window.$message.error("网络异常, 请稍后重试")
            break
        case 461:
            // 认证过期
            store.commit("logout")

            if (to.path != "/login") {
                router.push({
                    path: "/login",
                    query: query,
                })

                window.$message.info("登录信息过期，请重新登录")
            }

            break
        case 500:
            window.$message.error(message)
            break
        default:
            window.$message.error(message)
    }
}

// 请求拦截器
// 每次请求前，如果存在token则在请求头中携带token
instance.interceptors.request.use(
    (config) => {
        if (store.state.userinfo.token) {
            config.headers = {
                token: store.state.userinfo.token,
            }
        }

        return config
    },
    (error) => {
        Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
    // 请求成功
    (res) => {
        return Promise.resolve(res.data)
    },
    // 请求失败
    (error) => {
        const { response } = error

        let message = ""

        if (response) {
            message = response.data
            errorHandle(response.status, message)
        } else {
            // 处理断网的情况
            message = "网络异常, 请稍后重试"
            errorHandle(404, message)
        }

        return Promise.reject(message)
    }
)

export { instance as axios }
